<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="本节将详细分析Dubbo服务提供者的启动流程，请带着如下几个疑问进行本节的阅读，因为这几个问题将是接下来几篇文章分析的重点内容。  什么时候建立与注册中心的连接。 服务提供者什么时候向注册中心注册服务。 服务提供者与注册中心的心跳机制。">
<meta property="og:type" content="article">
<meta property="og:title" content="源码分析Dubbo服务提供者启动流程-上篇">
<meta property="og:url" content="https://www.codingw.net/posts/80b68fd8.html">
<meta property="og:site_name" content="中间件兴趣圈">
<meta property="og:description" content="本节将详细分析Dubbo服务提供者的启动流程，请带着如下几个疑问进行本节的阅读，因为这几个问题将是接下来几篇文章分析的重点内容。  什么时候建立与注册中心的连接。 服务提供者什么时候向注册中心注册服务。 服务提供者与注册中心的心跳机制。">
<meta property="og:locale">
<meta property="og:image" content="https://img-blog.csdn.net/20180601130421654?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70">
<meta property="og:image" content="https://img-blog.csdn.net/2018060113090393?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70">
<meta property="og:image" content="https://img-blog.csdn.net/20180601131950233?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70">
<meta property="og:image" content="https://img-blog.csdn.net/20180601132122916?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70">
<meta property="og:image" content="https://img-blog.csdn.net/20180601132156636?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70">
<meta property="og:image" content="https://img-blog.csdn.net/20180601132318446?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70">
<meta property="og:image" content="https://img-blog.csdn.net/20180601132342644?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70">
<meta property="article:published_time" content="2020-11-07T14:40:01.000Z">
<meta property="article:modified_time" content="2021-04-26T12:09:35.565Z">
<meta property="article:author" content="中间件兴趣圈">
<meta property="article:tag" content="中间件">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://img-blog.csdn.net/20180601130421654?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://www.codingw.net/posts/80b68fd8.html"/>





  <title>源码分析Dubbo服务提供者启动流程-上篇 | 中间件兴趣圈</title>
  








<meta name="generator" content="Hexo 5.4.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">中间件兴趣圈</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">微信搜『中间件兴趣圈』，回复『Java』获取200本优质电子书</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://www.codingw.net/posts/80b68fd8.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="中间件兴趣圈">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">源码分析Dubbo服务提供者启动流程-上篇</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-11-07T22:40:01+08:00">
                2020-11-07
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/dubbo/" itemprop="url" rel="index">
                    <span itemprop="name">dubbo</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/posts/80b68fd8.html" class="leancloud_visitors" data-flag-title="源码分析Dubbo服务提供者启动流程-上篇">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <div id="vip-container"><p>本节将详细分析Dubbo服务提供者的启动流程，请带着如下几个疑问进行本节的阅读，因为这几个问题将是接下来几篇文章分析的重点内容。</p>
<ol>
<li>什么时候建立与注册中心的连接。</li>
<li>服务提供者什么时候向注册中心注册服务。</li>
<li>服务提供者与注册中心的心跳机制。</li>
</ol>
<span id="more"></span>

<p>从上文中我们得知，服务提供者启动的核心入口为ServiceBean,本节将从源码级别详细剖析ServcieBean的实现原理，即Dubbo服务提供者的启动流程，ServiceBean的继承层次如图所示，dubbo:service标签的所有属性都被封装在此类图结构中。<br><img src="https://img-blog.csdn.net/20180601130421654?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70" alt="这里写图片描述"></p>
<h2 id="1、源码分析ServiceBean-afterPropertiesSet"><a href="#1、源码分析ServiceBean-afterPropertiesSet" class="headerlink" title="1、源码分析ServiceBean#afterPropertiesSet"></a>1、源码分析ServiceBean#afterPropertiesSet</h2><p> ServiceBean#afterPropertiesSet</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">if (getProvider() &#x3D;&#x3D; null) &#123;  &#x2F;&#x2F; @1</span><br><span class="line">    Map&lt;String, ProviderConfig&gt; provide</span><br><span class="line">             ConfigMap &#x3D; applicationContext &#x3D;&#x3D; null ? null : BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, ProviderConfig.class,   false, false); &#x2F;&#x2F; @2</span><br><span class="line">              &#x2F;&#x2F; ......  具体解析代码省略。</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>Step1：如果provider为空，说明dubbo:service标签未设置provider属性，如果一个dubbo:provider标签，则取该实例，如果存在多个dubbo:provider配置则provider属性不能为空，否则抛出异常：”Duplicate provider configs”。</p>
<p>ServiceBean#afterPropertiesSet</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">if (getApplication() &#x3D;&#x3D; null</span><br><span class="line">        &amp;&amp; (getProvider() &#x3D;&#x3D; null || getProvider().getApplication() &#x3D;&#x3D; null)) &#123;</span><br><span class="line">      Map&lt;String, ApplicationConfig&gt; applicationConfigMap &#x3D; applicationContext &#x3D;&#x3D; null ? null : BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, </span><br><span class="line">                 ApplicationConfig.class, false, false);</span><br><span class="line">       &#x2F;&#x2F; ...省略</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>Step2：如果application为空,则尝试从BeanFactory中查询dubbo:application实例，如果存在多个dubbo:application配置，则抛出异常：”Duplicate application configs”。</p>
<p>Step3：如果ServiceBean的module为空，则尝试从BeanFactory中查询dubbo:module实例，如果存在多个dubbo:module，则抛出异常：”Duplicate module configs: “。</p>
<p>Step4：尝试从BeanFactory中加载所有的注册中心，注意ServiceBean的List&lt; RegistryConfig&gt; registries属性，为注册中心集合。</p>
<p>Step5：尝试从BeanFacotry中加载一个监控中心，填充ServiceBean的MonitorConfig monitor属性，如果存在多个dubbo:monitor配置，则抛出”Duplicate monitor configs: “。</p>
<p>Step6：尝试从BeanFactory中加载所有的协议，注意：ServiceBean的List&lt; ProtocolConfig&gt; protocols是一个集合，也即一个服务可以通过多种协议暴露给消费者。</p>
<p>ServiceBean#afterPropertiesSet</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">if (getPath() &#x3D;&#x3D; null || getPath().length() &#x3D;&#x3D; 0) &#123;</span><br><span class="line">       if (beanName !&#x3D; null &amp;&amp; beanName.length() &gt; 0 &amp;&amp; getInterface() !&#x3D; null &amp;&amp; getInterface().length() &gt; 0  &amp;&amp; beanName.startsWith(getInterface())) &#123;</span><br><span class="line">                setPath(beanName);</span><br><span class="line">       &#125;</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>
<p>Step7：设置ServiceBean的path属性，path属性存放的是dubbo:service的beanName（dubbo:service id)。</p>
<p>ServiceBean#afterPropertiesSet</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">if (!isDelay()) &#123;</span><br><span class="line">     export();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>Step8：如果为启用延迟暴露机制，则调用export暴露服务。首先看一下isDelay的实现，然后重点分析export的实现原理（服务暴露的整个实现原理）。</p>
<p>ServiceBean#isDelay</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">private boolean isDelay() &#123;</span><br><span class="line">        Integer delay &#x3D; getDelay();</span><br><span class="line">        ProviderConfig provider &#x3D; getProvider();</span><br><span class="line">        if (delay &#x3D;&#x3D; null &amp;&amp; provider !&#x3D; null) &#123;</span><br><span class="line">            delay &#x3D; provider.getDelay();</span><br><span class="line">        &#125;</span><br><span class="line">        return supportedApplicationListener &amp;&amp; (delay &#x3D;&#x3D; null || delay &#x3D;&#x3D; -1);</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>如果有设置dubbo:service或dubbo:provider的属性delay，或配置delay为-1,都表示启用延迟机制，单位为毫秒，设置为-1，表示等到Spring容器初始化后再暴露服务。从这里也可以看出，Dubbo暴露服务的处理入口为ServiceBean#export—》ServiceConfig#export。</p>
<h3 id="1-1-源码分析ServiceConfig-export-暴露服务"><a href="#1-1-源码分析ServiceConfig-export-暴露服务" class="headerlink" title="1.1 源码分析ServiceConfig#export 暴露服务"></a>1.1 源码分析ServiceConfig#export 暴露服务</h3><p>调用链：ServiceBean#afterPropertiesSet——&gt;ServiceConfig#export</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">public synchronized void export() &#123;</span><br><span class="line">        if (provider !&#x3D; null) &#123;</span><br><span class="line">            if (export &#x3D;&#x3D; null) &#123;</span><br><span class="line">                export &#x3D; provider.getExport();</span><br><span class="line">            &#125;</span><br><span class="line">            if (delay &#x3D;&#x3D; null) &#123;</span><br><span class="line">                delay &#x3D; provider.getDelay();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        if (export !&#x3D; null &amp;&amp; !export) &#123;   &#x2F;&#x2F; @1</span><br><span class="line">            return;</span><br><span class="line">        &#125;</span><br><span class="line">        if (delay !&#x3D; null &amp;&amp; delay &gt; 0) &#123;    &#x2F;&#x2F; @2</span><br><span class="line">            delayExportExecutor.schedule(new Runnable() &#123;</span><br><span class="line">                @Override</span><br><span class="line">                public void run() &#123;</span><br><span class="line">                    doExport();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;, delay, TimeUnit.MILLISECONDS);</span><br><span class="line">        &#125; else &#123;</span><br><span class="line">            doExport();    &#x2F;&#x2F;@3</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：判断是否暴露服务，由dubbo:service export=”true|false”来指定。<br>代码@2：如果启用了delay机制，如果delay大于0，表示延迟多少毫秒后暴露服务，使用ScheduledExecutorService延迟调度，最终调用doExport方法。<br>代码@3：执行具体的暴露逻辑doExport，需要大家留意：delay=-1的处理逻辑（基于Spring事件机制触发）。</p>
<h3 id="1-2-源码分析ServiceConfig-doExport暴露服务"><a href="#1-2-源码分析ServiceConfig-doExport暴露服务" class="headerlink" title="1.2 源码分析ServiceConfig#doExport暴露服务"></a>1.2 源码分析ServiceConfig#doExport暴露服务</h3><p>调用链：ServiceBean#afterPropertiesSet—调用——&gt;ServiceConfig#export——&gt;ServiceConfig#doExport</p>
<p>ServiceConfig#checkDefault</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">private void checkDefault() &#123;</span><br><span class="line">        if (provider &#x3D;&#x3D; null) &#123;</span><br><span class="line">            provider &#x3D; new ProviderConfig();</span><br><span class="line">        &#125;</span><br><span class="line">        appendProperties(provider);</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>
<p>Step1:如果dubbo:servce标签也就是ServiceBean的provider属性为空，调用appendProperties方法，填充默认属性，其具体加载顺序：</p>
<ol>
<li>从系统属性加载对应参数值，参数键：dubbo.provider.属性名，System.getProperty。</li>
<li>加载属性配置文件的值。属性配置文件，可通过系统属性：dubbo.properties.file，如果该值未配置，则默认取dubbo.properties属性配置文件。</li>
</ol>
<p>ServiceConfig#doExport</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">if (ref instanceof GenericService) &#123;</span><br><span class="line">      interfaceClass &#x3D; GenericService.class;</span><br><span class="line">      if (StringUtils.isEmpty(generic)) &#123;</span><br><span class="line">           generic &#x3D; Boolean.TRUE.toString();</span><br><span class="line">      &#125;</span><br><span class="line"> &#125; else &#123;</span><br><span class="line">      try &#123;</span><br><span class="line">            interfaceClass &#x3D; Class.forName(interfaceName, true, Thread.currentThread()</span><br><span class="line">                        .getContextClassLoader());</span><br><span class="line">       &#125; catch (ClassNotFoundException e) &#123;</span><br><span class="line">            throw new IllegalStateException(e.getMessage(), e);</span><br><span class="line">       &#125;</span><br><span class="line">       checkInterfaceAndMethods(interfaceClass, methods);</span><br><span class="line">       checkRef();</span><br><span class="line">       generic &#x3D; Boolean.FALSE.toString();</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>
<p>Step2：校验ref与interface属性。如果ref是GenericService，则为dubbo的泛化实现，然后验证interface接口与ref引用的类型是否一致。</p>
<p>ServiceConfig#doExport</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">if (local !&#x3D; null) &#123;</span><br><span class="line">      if (&quot;true&quot;.equals(local)) &#123;</span><br><span class="line">            local &#x3D; interfaceName + &quot;Local&quot;;</span><br><span class="line">      &#125;</span><br><span class="line">      Class&lt;?&gt; localClass;</span><br><span class="line">      try &#123;</span><br><span class="line">             localClass &#x3D; ClassHelper.forNameWithThreadContextClassLoader(local);</span><br><span class="line">       &#125; catch (ClassNotFoundException e) &#123;</span><br><span class="line">            throw new IllegalStateException(e.getMessage(), e);</span><br><span class="line">       &#125;</span><br><span class="line">      if (!interfaceClass.isAssignableFrom(localClass)) &#123;</span><br><span class="line">           throw new IllegalStateException(&quot;The local implementation class &quot; + localClass.getName() + &quot; not implement interface &quot; + interfaceName);</span><br><span class="line">       &#125;</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>
<p>Step3：dubbo:service local机制，已经废弃，被stub属性所替换。<br>Step4：处理本地存根Stub，&lt;dubbo:service 的stub属性，可以设置为true，此时Stub的类名为：interface+Stub，stub也可以指定自定义的全类名。本地存根说明如图所示（Dubbo官方文档）<br><img src="https://img-blog.csdn.net/2018060113090393?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70" alt="这里写图片描述"><br>ServiceConfig#doExport</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">checkApplication();</span><br><span class="line">checkRegistry();</span><br><span class="line">checkProtocol();</span><br><span class="line">appendProperties(this);</span><br></pre></td></tr></table></figure>
<p>Step5：校验ServiceBean的application、registry、protocol是否为空，并从系统属性（优先）、资源文件中填充其属性。<br> 系统属性、资源文件属性的配置如下：<br> application     dubbo.application.属性名，例如    dubbo.application.name<br> registry          dubbo.registry.属性名，例如    dubbo.registry.address<br> protocol         dubbo.protocol.属性名，例如 dubbo.protocol.port<br> service           dubbo.service.属性名，例如 dubbo.service.stub</p>
<p>ServiceConfig#doExport</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">checkStubAndMock(interfaceClass);</span><br></pre></td></tr></table></figure>
<p>Step6：校验stub、mock类的合理性，是否是interface的实现类。</p>
<p>ServiceConfig#doExport</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">doExportUrls();</span><br></pre></td></tr></table></figure>
<p>Step7：执行doExportUrls()方法暴露服务，接下来会重点分析该方法。</p>
<p> ServiceConfig#doExport</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">ProviderModel providerModel &#x3D; new ProviderModel(getUniqueServiceName(), this, ref);</span><br><span class="line">ApplicationModel.initProviderModel(getUniqueServiceName(), providerModel);</span><br></pre></td></tr></table></figure>
<p>Step8：将服务提供者信息注册到ApplicationModel实例中。</p>
<h3 id="1-3-源码分析ServiceConfig-doExportUrls暴露服务具体实现逻辑"><a href="#1-3-源码分析ServiceConfig-doExportUrls暴露服务具体实现逻辑" class="headerlink" title="1.3 源码分析ServiceConfig#doExportUrls暴露服务具体实现逻辑"></a>1.3 源码分析ServiceConfig#doExportUrls暴露服务具体实现逻辑</h3><p> 调用链：ServiceBean#afterPropertiesSet——&gt;ServiceConfig#export——&gt;ServiceConfig#doExport</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">private void doExportUrls() &#123;</span><br><span class="line">        List&lt;URL&gt; registryURLs &#x3D; loadRegistries(true);  &#x2F;&#x2F; @1</span><br><span class="line">        for (ProtocolConfig protocolConfig : protocols) &#123;</span><br><span class="line">            doExportUrlsFor1Protocol(protocolConfig, registryURLs);    &#x2F;&#x2F; @2</span><br><span class="line">        &#125;</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：首先遍历ServiceBean的List&lt; RegistryConfig&gt; registries（所有注册中心的配置信息），然后将地址封装成URL对象，关于注册中心的所有配置属性，最终转换成url的属性(?属性名=属性值)，loadRegistries(true)，参数的意思：true，代表服务提供者，false：代表服务消费者，如果是服务提供者，则检测注册中心的配置，如果配置了register=”false”，则忽略该地址，如果是服务消费者，并配置了subscribe=”false”则表示不从该注册中心订阅服务，故也不返回，一个注册中心URL示例：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">registry:&#x2F;&#x2F;127.0.0.1:2181&#x2F;com.alibaba.dubbo.registry.RegistryService?application&#x3D;demo-provider&amp;dubbo&#x3D;2.0.0&amp;pid&#x3D;7072&amp;qos.port&#x3D;22222&amp;registry&#x3D;zookeeper&amp;timestamp&#x3D;1527308268041</span><br></pre></td></tr></table></figure>

<p> 代码@2：然后遍历配置的所有协议，根据每个协议，向注册中心暴露服务，接下来重点分析doExportUrlsFor1Protocol方法的实现细节。</p>
<h3 id="1-4-源码分析doExportUrlsFor1Protocol"><a href="#1-4-源码分析doExportUrlsFor1Protocol" class="headerlink" title="1.4 源码分析doExportUrlsFor1Protocol"></a>1.4 源码分析doExportUrlsFor1Protocol</h3><p> 调用链：ServiceBean#afterPropertiesSet——&gt;ServiceConfig#export——&gt;ServiceConfig#doExport——&gt;ServiceConfig#doExportUrlsFor1Protocol<br> ServiceConfig#doExportUrlsFor1Protocol</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">String name &#x3D; protocolConfig.getName();</span><br><span class="line">if (name &#x3D;&#x3D; null || name.length() &#x3D;&#x3D; 0) &#123;</span><br><span class="line">     name &#x3D; &quot;dubbo&quot;;</span><br><span class="line">&#125;</span><br><span class="line">Map&lt;String, String&gt; map &#x3D; new HashMap&lt;String, String&gt;();</span><br><span class="line">map.put(Constants.SIDE_KEY, Constants.PROVIDER_SIDE);</span><br><span class="line">map.put(Constants.DUBBO_VERSION_KEY, Version.getVersion());</span><br><span class="line">map.put(Constants.TIMESTAMP_KEY, String.valueOf(System.currentTimeMillis()));</span><br><span class="line">if (ConfigUtils.getPid() &gt; 0) &#123;</span><br><span class="line">    map.put(Constants.PID_KEY, String.valueOf(ConfigUtils.getPid()));</span><br><span class="line">&#125;</span><br><span class="line">appendParameters(map, application);</span><br><span class="line">appendParameters(map, module);</span><br><span class="line">appendParameters(map, provider, Constants.DEFAULT_KEY);</span><br><span class="line">appendParameters(map, protocolConfig);</span><br><span class="line">appendParameters(map, this);</span><br></pre></td></tr></table></figure>
<p>Step1：用Map存储该协议的所有配置参数，包括协议名称、dubbo版本、当前系统时间戳、进程ID、application配置、module配置、默认服务提供者参数(ProviderConfig)、协议配置、服务提供Dubbo:service的属性。</p>
<p> ServiceConfig#doExportUrlsFor1Protocol</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br></pre></td><td class="code"><pre><span class="line">if (methods !&#x3D; null &amp;&amp; !methods.isEmpty()) &#123;</span><br><span class="line">            for (MethodConfig method : methods) &#123;</span><br><span class="line">                appendParameters(map, method, method.getName());</span><br><span class="line">                String retryKey &#x3D; method.getName() + &quot;.retry&quot;;</span><br><span class="line">                if (map.containsKey(retryKey)) &#123;</span><br><span class="line">                    String retryValue &#x3D; map.remove(retryKey);</span><br><span class="line">                    if (&quot;false&quot;.equals(retryValue)) &#123;</span><br><span class="line">                        map.put(method.getName() + &quot;.retries&quot;, &quot;0&quot;);</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">                List&lt;ArgumentConfig&gt; arguments &#x3D; method.getArguments();</span><br><span class="line">                if (arguments !&#x3D; null &amp;&amp; !arguments.isEmpty()) &#123;</span><br><span class="line">                    for (ArgumentConfig argument : arguments) &#123;</span><br><span class="line">                        &#x2F;&#x2F; convert argument type</span><br><span class="line">                        if (argument.getType() !&#x3D; null &amp;&amp; argument.getType().length() &gt; 0) &#123;</span><br><span class="line">                            Method[] methods &#x3D; interfaceClass.getMethods();</span><br><span class="line">                            &#x2F;&#x2F; visit all methods</span><br><span class="line">                            if (methods !&#x3D; null &amp;&amp; methods.length &gt; 0) &#123;</span><br><span class="line">                                for (int i &#x3D; 0; i &lt; methods.length; i++) &#123;</span><br><span class="line">                                    String methodName &#x3D; methods[i].getName();</span><br><span class="line">                                    &#x2F;&#x2F; target the method, and get its signature</span><br><span class="line">                                    if (methodName.equals(method.getName())) &#123;</span><br><span class="line">                                        Class&lt;?&gt;[] argtypes &#x3D; methods[i].getParameterTypes();</span><br><span class="line">                                        &#x2F;&#x2F; one callback in the method</span><br><span class="line">                                        if (argument.getIndex() !&#x3D; -1) &#123;</span><br><span class="line">                                            if (argtypes[argument.getIndex()].getName().equals(argument.getType())) &#123;</span><br><span class="line">                                                appendParameters(map, argument, method.getName() + &quot;.&quot; + argument.getIndex());</span><br><span class="line">                                            &#125; else &#123;</span><br><span class="line">                                                throw new IllegalArgumentException(&quot;argument config error : the index attribute and type attribute not match :index :&quot; + argument.getIndex() + &quot;, type:&quot; + </span><br><span class="line">                                                      argument.getType());</span><br><span class="line">                                            &#125;</span><br><span class="line">                                        &#125; else &#123;</span><br><span class="line">                                            &#x2F;&#x2F; multiple callbacks in the method</span><br><span class="line">                                            for (int j &#x3D; 0; j &lt; argtypes.length; j++) &#123;</span><br><span class="line">                                                Class&lt;?&gt; argclazz &#x3D; argtypes[j];</span><br><span class="line">                                                if (argclazz.getName().equals(argument.getType())) &#123;</span><br><span class="line">                                                    appendParameters(map, argument, method.getName() + &quot;.&quot; + j);</span><br><span class="line">                                                    if (argument.getIndex() !&#x3D; -1 &amp;&amp; argument.getIndex() !&#x3D; j) &#123;</span><br><span class="line">                                                        throw new IllegalArgumentException(&quot;argument config error : the index attribute and type attribute not match :index :&quot; + argument.getIndex() + &quot;, </span><br><span class="line">                                                             type:&quot; + argument.getType());</span><br><span class="line">                                                    &#125;</span><br><span class="line">                                                &#125;</span><br><span class="line">                                            &#125;</span><br><span class="line">                                        &#125;</span><br><span class="line">                                    &#125;</span><br><span class="line">                                &#125;</span><br><span class="line">                            &#125;</span><br><span class="line">                        &#125; else if (argument.getIndex() !&#x3D; -1) &#123;</span><br><span class="line">                            appendParameters(map, argument, method.getName() + &quot;.&quot; + argument.getIndex());</span><br><span class="line">                        &#125; else &#123;</span><br><span class="line">                            throw new IllegalArgumentException(&quot;argument config must set index or type attribute.eg: &lt;dubbo:argument index&#x3D;&#39;0&#39; ...&#x2F;&gt; or &lt;dubbo:argument type&#x3D;xxx ...&#x2F;&gt;&quot;);</span><br><span class="line">                        &#125;</span><br><span class="line"></span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; &#x2F;&#x2F; end of methods for</span><br><span class="line">        &#125;</span><br></pre></td></tr></table></figure>
<p>Step2：如果dubbo:service有dubbo:method子标签，则dubbo:method以及其子标签的配置属性，都存入到Map中，属性名称加上对应的方法名作为前缀。dubbo:method的子标签dubbo:argument,其键为方法名.参数序号。</p>
<p>ServiceConfig#doExportUrlsFor1Protocol</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">if (ProtocolUtils.isGeneric(generic)) &#123;</span><br><span class="line">      map.put(Constants.GENERIC_KEY, generic);</span><br><span class="line">      map.put(Constants.METHODS_KEY, Constants.ANY_VALUE);</span><br><span class="line"> &#125; else &#123;</span><br><span class="line">      String revision &#x3D; Version.getVersion(interfaceClass, version);</span><br><span class="line">      if (revision !&#x3D; null &amp;&amp; revision.length() &gt; 0) &#123;</span><br><span class="line">          map.put(&quot;revision&quot;, revision);</span><br><span class="line">      &#125;</span><br><span class="line">      String[] methods &#x3D; Wrapper.getWrapper(interfaceClass).getMethodNames();</span><br><span class="line">      if (methods.length &#x3D;&#x3D; 0) &#123;</span><br><span class="line">           logger.warn(&quot;NO method found in service interface &quot; + interfaceClass.getName());</span><br><span class="line">           map.put(Constants.METHODS_KEY, Constants.ANY_VALUE);</span><br><span class="line">      &#125; else &#123;</span><br><span class="line">           map.put(Constants.METHODS_KEY, StringUtils.join(new HashSet&lt;String&gt;(Arrays.asList(methods)), &quot;,&quot;));</span><br><span class="line">      &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>Step3：添加methods键值对，存放dubbo:service的所有方法名，多个方法名用,隔开，如果是泛化实现，填充genric=true,methods为”*”；</p>
<p>ServiceConfig#doExportUrlsFor1Protocol</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">if (!ConfigUtils.isEmpty(token)) &#123;</span><br><span class="line">      if (ConfigUtils.isDefault(token)) &#123;</span><br><span class="line">            map.put(Constants.TOKEN_KEY, UUID.randomUUID().toString());</span><br><span class="line">       &#125; else &#123;</span><br><span class="line">            map.put(Constants.TOKEN_KEY, token);</span><br><span class="line">       &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>Step4:根据是否开启令牌机制，如果开启，设置token键，值为静态值或uuid。</p>
<p>ServiceConfig#doExportUrlsFor1Protocol</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">if (Constants.LOCAL_PROTOCOL.equals(protocolConfig.getName())) &#123;</span><br><span class="line">       protocolConfig.setRegister(false);</span><br><span class="line">       map.put(&quot;notify&quot;, &quot;false&quot;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>Step5:如果协议为本地协议(injvm)，则设置protocolConfig#register属性为false，表示不向注册中心注册服务，在map中存储键为notify,值为false,表示当注册中心监听到服务提供者发送变化（服务提供者增加、服务提供者减少等事件时不通知。</p>
<p>ServiceConfig#doExportUrlsFor1Protocol</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F; export service</span><br><span class="line">String contextPath &#x3D; protocolConfig.getContextpath();</span><br><span class="line">if ((contextPath &#x3D;&#x3D; null || contextPath.length() &#x3D;&#x3D; 0) &amp;&amp; provider !&#x3D; null) &#123;</span><br><span class="line">     contextPath &#x3D; provider.getContextpath();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>Step6:设置协议的contextPath,如果未配置，默认为/interfacename</p>
<p>ServiceConfig#doExportUrlsFor1Protocol</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">String host &#x3D; this.findConfigedHosts(protocolConfig, registryURLs, map);</span><br><span class="line">Integer port &#x3D; this.findConfigedPorts(protocolConfig, name, map);</span><br></pre></td></tr></table></figure>
<p>Step7：解析服务提供者的IP地址与端口。<br>服务IP地址解析顺序：（序号越小越优先）</p>
<ol>
<li>系统环境变量，变量名：DUBBO_DUBBO_IP_TO_BIND  </li>
<li>系统属性,变量名：DUBBO_DUBBO_IP_TO_BIND</li>
<li>系统环境变量，变量名：DUBBO_IP_TO_BIND</li>
<li>系统属性，变量名：DUBBO_IP_TO_BIND</li>
<li>dubbo:protocol 标签的host属性  –》 dubbo:provider 标签的host属性</li>
<li>默认网卡IP地址，通过InetAddress.getLocalHost().getHostAddress()获取，如果IP地址不符合要求，继续下一个匹配。</li>
</ol>
<p>判断IP地址是否符合要求的标准是：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">public static boolean isInvalidLocalHost(String host) &#123;</span><br><span class="line">     return host &#x3D;&#x3D; null</span><br><span class="line">             || host.length() &#x3D;&#x3D; 0</span><br><span class="line">             || host.equalsIgnoreCase(&quot;localhost&quot;)</span><br><span class="line">             || host.equals(&quot;0.0.0.0&quot;)</span><br><span class="line">             || (LOCAL_IP_PATTERN.matcher(host).matches());</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>
<ol start="7">
<li>选择第一个可用网卡，其实现方式是建立socket，连接注册中心，获取socket的IP地址。其代码：<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">Socket socket &#x3D; new Socket();</span><br><span class="line">        try &#123;</span><br><span class="line">              SocketAddress addr &#x3D; new InetSocketAddress(registryURL.getHost(), registryURL.getPort());</span><br><span class="line">              socket.connect(addr, 1000);</span><br><span class="line">              hostToBind &#x3D; socket.getLocalAddress().getHostAddress();</span><br><span class="line">              break;</span><br><span class="line">         &#125; finally &#123;</span><br><span class="line">              try &#123;</span><br><span class="line">                      socket.close();</span><br><span class="line">              &#125; catch (Throwable e) &#123;</span><br><span class="line">              &#125;</span><br><span class="line">        &#125;</span><br></pre></td></tr></table></figure>
服务提供者端口解析顺序：（序号越小越优先）</li>
<li>系统环境变量，变量名：DUBBO_DUBBO_PORT_TO_BIND</li>
<li>系统属性，变量名：DUBBO_DUBBO_PORT_TO_BIND</li>
<li>系统环境变量，变量名：DUBBO_PORT_TO_BIND</li>
<li>系统属性，变量名DUBBO_PORT_TO_BIND</li>
<li>dubbo:protocol标签port属性、dubbo:provider标签的port属性。</li>
<li>随机选择一个端口。</li>
</ol>
<p> ServiceConfig#doExportUrlsFor1Protocol</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">URL url &#x3D; new URL(name, host, port, (contextPath &#x3D;&#x3D; null || contextPath.length() &#x3D;&#x3D; 0 ? &quot;&quot; : contextPath + &quot;&#x2F;&quot;) + path, map);</span><br></pre></td></tr></table></figure>
<p> Step8：根据协议名称、协议host、协议端口、contextPath、相关配置属性（application、module、provider、protocolConfig、service及其子标签）构建服务提供者URI。<br> URL运行效果图:<br><img src="https://img-blog.csdn.net/20180601131950233?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70" alt="这里写图片描述"><br> 以dubbo协议为例，展示最终服务提供者的URL信息如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">dubbo:&#x2F;&#x2F;192.168.56.1:20880&#x2F;com.alibaba.dubbo.demo.DemoService?anyhost&#x3D;true&amp;application&#x3D;demo-provider&amp;bind.ip&#x3D;192.168.56.1&amp;bind.port&#x3D;20880&amp;dubbo&#x3D;2.0.0&amp;generic&#x3D;false&amp;interface&#x3D;com.alibaba.dubbo.demo.DemoService&amp;methods&#x3D;sayHello&amp;pid&#x3D;5916&amp;qos.port&#x3D;22222&amp;side&#x3D;provider&amp;timestamp&#x3D;1527168070857</span><br></pre></td></tr></table></figure>

<p> ServiceConfig#doExportUrlsFor1Protocol</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">String scope &#x3D; url.getParameter(Constants.SCOPE_KEY);</span><br><span class="line">&#x2F;&#x2F; don&#39;t export when none is configured</span><br><span class="line">if (!Constants.SCOPE_NONE.toString().equalsIgnoreCase(scope)) &#123;</span><br><span class="line">     &#x2F;&#x2F; 接口暴露实现逻辑</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>Step9：获取dubbo:service标签的scope属性，其可选值为none(不暴露)、local(本地)、remote(远程)，如果配置为none，则不暴露。默认为local。</p>
<p> ServiceConfig#doExportUrlsFor1Protocol</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F; export to local if the config is not remote (export to remote only when config is remote)</span><br><span class="line">if (!Constants.SCOPE_REMOTE.toString().equalsIgnoreCase(scope)) &#123;     &#x2F;&#x2F; @1</span><br><span class="line">       exportLocal(url);</span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F; export to remote if the config is not local (export to local only when config is local)</span><br><span class="line">if (!Constants.SCOPE_LOCAL.toString().equalsIgnoreCase(scope)) &#123;     &#x2F;&#x2F; @2</span><br><span class="line">        if (logger.isInfoEnabled()) &#123;</span><br><span class="line">              logger.info(&quot;Export dubbo service &quot; + interfaceClass.getName() + &quot; to url &quot; + url);</span><br><span class="line">         &#125;</span><br><span class="line">        if (registryURLs !&#x3D; null &amp;&amp; !registryURLs.isEmpty()) &#123;   &#x2F;&#x2F; @3</span><br><span class="line">              for (URL registryURL : registryURLs) &#123;</span><br><span class="line">                    url &#x3D; url.addParameterIfAbsent(Constants.DYNAMIC_KEY, registryURL.getParameter(Constants.DYNAMIC_KEY));  &#x2F;&#x2F; @4</span><br><span class="line">                    URL monitorUrl &#x3D; loadMonitor(registryURL);       &#x2F;&#x2F; @5</span><br><span class="line">                    if (monitorUrl !&#x3D; null) &#123;</span><br><span class="line">                        url &#x3D; url.addParameterAndEncoded(Constants.MONITOR_KEY, monitorUrl.toFullString());  </span><br><span class="line">                    &#125;</span><br><span class="line">                    if (logger.isInfoEnabled()) &#123;</span><br><span class="line">                        logger.info(&quot;Register dubbo service &quot; + interfaceClass.getName() + &quot; url &quot; + url + &quot; to registry &quot; + registryURL);</span><br><span class="line">                    &#125;</span><br><span class="line">                   Invoker&lt;?&gt; invoker &#x3D; proxyFactory.getInvoker(ref, (Class) interfaceClass, registryURL.addParameterAndEncoded(Constants.EXPORT_KEY, url.toFullString()));  &#x2F;&#x2F; @6</span><br><span class="line">                   DelegateProviderMetaDataInvoker wrapperInvoker &#x3D; new DelegateProviderMetaDataInvoker(invoker, this);    </span><br><span class="line">                   Exporter&lt;?&gt; exporter &#x3D; protocol.export(wrapperInvoker);    &#x2F;&#x2F; @7</span><br><span class="line">                   exporters.add(exporter);</span><br><span class="line">               &#125;</span><br><span class="line">         &#125; else &#123;</span><br><span class="line">               Invoker&lt;?&gt; invoker &#x3D; proxyFactory.getInvoker(ref, (Class) interfaceClass, url);</span><br><span class="line">               DelegateProviderMetaDataInvoker wrapperInvoker &#x3D; new DelegateProviderMetaDataInvoker(invoker, this);</span><br><span class="line">               Exporter&lt;?&gt; exporter &#x3D; protocol.export(wrapperInvoker);</span><br><span class="line">               exporters.add(exporter);</span><br><span class="line">         &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>Step10：根据scope来暴露服务，如果scope不配置，则默认本地与远程都会暴露，如果配置成local或remote，那就只能是二选一。</p>
<ul>
<li><p>代码@1：如果scope不为remote，则先在本地暴露(injvm):，具体暴露服务的具体实现，将在remote 模式中详细分析。</p>
</li>
<li><p>代码@2：如果scope不为local,则将服务暴露在远程。 </p>
</li>
<li><p>代码@3：remote方式，检测当前配置的所有注册中心，如果注册中心不为空，则遍历注册中心，将服务依次在不同的注册中心进行注册。</p>
</li>
<li><p>代码@4：如果dubbo:service的dynamic属性未配置， 尝试取dubbo:registry的dynamic属性，该属性的作用是否启用动态注册，如果设置为false，服务注册后，其状态显示为disable，需要人工启用，当服务不可用时，也不会自动移除，同样需要人工处理，此属性不要在生产环境上配置。</p>
</li>
<li><p>代码@5：根据注册中心url(注册中心url)，构建监控中心的URL，如果监控中心URL不为空，则在服务提供者URL上追加monitor，其值为监控中心url(已编码)。</p>
</li>
<li><p>如果dubbo spring xml配置文件中没有配置监控中心(dubbo:monitor),如果从系统属性-Ddubbo.monitor.address，-Ddubbo.monitor.protocol构建MonitorConfig对象，否则从dubbo的properties配置文件中寻找这个两个参数，如果没有配置，则返回null。</p>
</li>
<li><p>如果有配置，则追加相关参数，dubbo:monitor标签只有两个属性：address、protocol，其次会追加interface(MonitorService)、协议等。</p>
</li>
<li><p>代码@6：通过动态代理机制创建Invoker，dubbo的远程调用实现类。<br><img src="https://img-blog.csdn.net/20180601132122916?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70" alt="这里写图片描述"><br> Dubbo远程调用器如何构建，这里不详细深入，重点关注WrapperInvoker的url为:registry://127.0.0.1:2181/com.alibaba.dubbo.registry.RegistryService?application=demo-provider&amp;dubbo=2.0.0&amp;export=dubbo%3A%2F%2F192.168.56.1%3A20880%2Fcom.alibaba.dubbo.demo.DemoService%3Fanyhost%3Dtrue%26application%3Ddemo-provider%26bind.ip%3D192.168.56.1%26bind.port%3D20880%26dubbo%3D2.0.0%26generic%3Dfalse%26interface%3Dcom.alibaba.dubbo.demo.DemoService%26methods%3DsayHello%26pid%3D6328%26qos.port%3D22222%26side%3Dprovider%26timestamp%3D1527255510215&amp;pid=6328&amp;qos.port=22222&amp;registry=zookeeper&amp;timestamp=1527255510202，这里有两个重点值得关注：</p>
</li>
<li><p>path属性：com.alibaba.dubbo.registry.RegistryService，注册中心也类似于服务提供者。</p>
</li>
<li><p>export属性：值为服务提供者的URL，为什么需要关注这个URL呢？请看代码@7，protocol属性为Protocol$Adaptive，Dubbo在加载组件实现类时采用SPI(插件机制，有关于插件机制，在该专题后续文章将重点分析)，在这里我们只需要知道，根据URL冒号之前的协议名将会调用相应的方法。<br><img src="https://img-blog.csdn.net/20180601132156636?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70" alt="这里写图片描述"><br> 其映射关系(列出与服务启动相关协议实现类)：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">dubbo&#x3D;com.alibaba.dubbo.rpc.protocol.dubbo.DubboProtocol       &#x2F;&#x2F;文件位于dubbo-rpc-dubbo&#x2F;src&#x2F;main&#x2F;resources&#x2F;META-INF&#x2F;dubbo&#x2F;internal&#x2F;com.alibaba.dubbo.rpc.Protocol</span><br><span class="line">registry&#x3D;com.alibaba.dubbo.registry.integration.RegistryProtocol   &#x2F;&#x2F;文件位于dubbo-registry-api&#x2F;src&#x2F;main&#x2F;resources&#x2F;META-INF&#x2F;dubbo&#x2F;internal&#x2F;com.alibaba.dubbo.rpc.Protocol</span><br></pre></td></tr></table></figure>

<p> 代码@7：根据代码@6的分析，将调用RegistryProtocol#export方法。</p>
</li>
</ul>
<h3 id="1-5-源码分析RegistryProtocol-export方法"><a href="#1-5-源码分析RegistryProtocol-export方法" class="headerlink" title="1.5 源码分析RegistryProtocol#export方法"></a>1.5 源码分析RegistryProtocol#export方法</h3><p> 调用链：ServiceBean#afterPropertiesSet——&gt;ServiceConfig#export——&gt;ServiceConfig#doExport——&gt;ServiceConfig#doExportUrlsFor1Protocol——&gt;RegistryProtocol#export</p>
<p> RegistryProtocol#export</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line">@Override</span><br><span class="line">    public &lt;T&gt; Exporter&lt;T&gt; export(final Invoker&lt;T&gt; originInvoker) throws RpcException &#123;</span><br><span class="line">        &#x2F;&#x2F;export invoker</span><br><span class="line">        final ExporterChangeableWrapper&lt;T&gt; exporter &#x3D; doLocalExport(originInvoker);   &#x2F;&#x2F; @1</span><br><span class="line"></span><br><span class="line">        URL registryUrl &#x3D; getRegistryUrl(originInvoker);       &#x2F;&#x2F; @2</span><br><span class="line"></span><br><span class="line">        &#x2F;&#x2F;registry provider</span><br><span class="line">        final Registry registry &#x3D; getRegistry(originInvoker);                          &#x2F;&#x2F; @3</span><br><span class="line">        final URL registedProviderUrl &#x3D; getRegistedProviderUrl(originInvoker);     &#x2F;&#x2F; @4start</span><br><span class="line"></span><br><span class="line">        &#x2F;&#x2F;to judge to delay publish whether or not</span><br><span class="line">        boolean register &#x3D; registedProviderUrl.getParameter(&quot;register&quot;, true);  </span><br><span class="line"></span><br><span class="line">        ProviderConsumerRegTable.registerProvider(originInvoker, registryUrl, registedProviderUrl);</span><br><span class="line"></span><br><span class="line">        if (register) &#123;  </span><br><span class="line">            register(registryUrl, registedProviderUrl);      &#x2F;&#x2F; @4 end</span><br><span class="line">            ProviderConsumerRegTable.getProviderWrapper(originInvoker).setReg(true);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        &#x2F;&#x2F; Subscribe the override data</span><br><span class="line">        &#x2F;&#x2F; FIXME When the provider subscribes, it will affect the scene : a certain JVM exposes the service and call the same service. Because the subscribed is cached key with the name of the service, it causes the subscription information to cover.</span><br><span class="line">        final URL overrideSubscribeUrl &#x3D; getSubscribedOverrideUrl(registedProviderUrl);          &#x2F;&#x2F; @5 start</span><br><span class="line">        final OverrideListener overrideSubscribeListener &#x3D; new OverrideListener(overrideSubscribeUrl, originInvoker);</span><br><span class="line">        overrideListeners.put(overrideSubscribeUrl, overrideSubscribeListener);</span><br><span class="line">        registry.subscribe(overrideSubscribeUrl, overrideSubscribeListener);            &#x2F;&#x2F; @5 end</span><br><span class="line">        &#x2F;&#x2F;Ensure that a new exporter instance is returned every time export</span><br><span class="line">        return new DestroyableExporter&lt;T&gt;(exporter, originInvoker, overrideSubscribeUrl, registedProviderUrl);</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：启动服务提供者服务，监听指定端口，准备服务消费者的请求，这里其实就是从WrapperInvoker中的url(注册中心url)中提取export属性，描述服务提供者的url，然后启动服务提供者。<br><img src="https://img-blog.csdn.net/20180601132318446?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70" alt="这里写图片描述"><br>从上图中，可以看出，将调用DubboProtocol#export完成dubbo服务的启动，利用netty构建一个微型服务端，监听端口，准备接受服务消费者的网络请求，本节旨在梳理其启动流程，具体实现细节，将在后续章节中详解，这里我们只要知道，&lt; dubbo:protocol name=”dubbo” port=”20880” /&gt;,会再此次监听该端口，然后将dubbo:service的服务handler加入到命令处理器中，当有消息消费者连接该端口时，通过网络解包，将需要调用的服务和参数等信息解析处理后，转交给对应的服务实现类处理即可。<br> 代码@2：获取真实注册中心的URL,例如zookeeper注册中心的</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">URL:zookeeper:&#x2F;&#x2F;127.0.0.1:2181&#x2F;com.alibaba.dubbo.registry.RegistryService?application&#x3D;demo-provider&amp;dubbo&#x3D;2.0.0&amp;export&#x3D;dubbo%3A%2F%2F192.168.56.1%3A20880%2Fcom.alibaba.dubbo.demo.DemoService%3Fanyhost%3Dtrue%26application%3Ddemo-provider%26bind.ip%3D192.168.56.1%26bind.port%3D20880%26dubbo%3D2.0.0%26generic%3Dfalse%26interface%3Dcom.alibaba.dubbo.demo.DemoService%26methods%3DsayHello%26pid%3D10252%26qos.port%3D22222%26side%3Dprovider%26timestamp%3D1527263060882&amp;pid&#x3D;10252&amp;qos.port&#x3D;22222&amp;timestamp&#x3D;1527263060867</span><br></pre></td></tr></table></figure>

<p>代码@3：根据注册中心URL，从注册中心工厂中获取指定的注册中心实现类：zookeeper注册中心的实现类为：ZookeeperRegistry</p>
<p>代码@4：获取服务提供者URL中的register属性，如果为true,则调用注册中心的ZookeeperRegistry#register方法向注册中心注册服务（实际由其父类FailbackRegistry实现）。</p>
<p>代码@5：服务提供者向注册中心订阅自己，主要是为了服务提供者URL发送变化后重新暴露服务，当然，会将dubbo:reference的check属性设置为false。</p>
<p>到这里就对文章开头提到的问题1，问题2做了一个解答，其与注册中心的心跳机制等将在后续章节中详细分析。</p>
<p>文字看起来可能不是很直观，现整理一下Dubbo服务提供者启动流程图如下：<br><img src="https://img-blog.csdn.net/20180601132342644?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70" alt="这里写图片描述"></p>
<p>本文重点梳理了Dubbo服务提供者启动流程，其中Dubbo服务提供者在指定端口监听服务的启动流程将在下一节中详细分析。</p>
</div>

			<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
			<script>
			var isMobile = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i);
			if (!isMobile) {
			    var btw = new BTWPlugin();
			    btw.init({
			        "id": "vip-container",
			        "blogId": "18019-1573088808868-542",
			        "name": "中间件兴趣圈",
			        "qrcode": "https://img-blog.csdnimg.cn/20190314214003962.jpg",
			        "keyword": "more"
			    });
			}
			</script>
		
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/posts/380ae8bd.html" rel="next" title="源码分析Dubbo服务提供者启动流程-下篇">
                <i class="fa fa-chevron-left"></i> 源码分析Dubbo服务提供者启动流程-下篇
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/posts/22a2e460.html" rel="prev" title="源码分析Dubbo Invoker概述----服务发现、集群、负载均衡、路由体系">
                源码分析Dubbo Invoker概述----服务发现、集群、负载均衡、路由体系 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">139</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1%E3%80%81%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90ServiceBean-afterPropertiesSet"><span class="nav-number">1.</span> <span class="nav-text">1、源码分析ServiceBean#afterPropertiesSet</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-1-%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90ServiceConfig-export-%E6%9A%B4%E9%9C%B2%E6%9C%8D%E5%8A%A1"><span class="nav-number">1.1.</span> <span class="nav-text">1.1 源码分析ServiceConfig#export 暴露服务</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-2-%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90ServiceConfig-doExport%E6%9A%B4%E9%9C%B2%E6%9C%8D%E5%8A%A1"><span class="nav-number">1.2.</span> <span class="nav-text">1.2 源码分析ServiceConfig#doExport暴露服务</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-3-%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90ServiceConfig-doExportUrls%E6%9A%B4%E9%9C%B2%E6%9C%8D%E5%8A%A1%E5%85%B7%E4%BD%93%E5%AE%9E%E7%8E%B0%E9%80%BB%E8%BE%91"><span class="nav-number">1.3.</span> <span class="nav-text">1.3 源码分析ServiceConfig#doExportUrls暴露服务具体实现逻辑</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-4-%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90doExportUrlsFor1Protocol"><span class="nav-number">1.4.</span> <span class="nav-text">1.4 源码分析doExportUrlsFor1Protocol</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-5-%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90RegistryProtocol-export%E6%96%B9%E6%B3%95"><span class="nav-number">1.5.</span> <span class="nav-text">1.5 源码分析RegistryProtocol#export方法</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">中间件兴趣圈</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("NNEhOL0iOcflg8f1U3HUqiCq-gzGzoHsz", "7kSmkbbb3DktmHALlShDsBUF");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

</body>
</html>
